<!--
 * @Description: 实时监测
 * @Author: Ronda
 * @Date: 2022-02-16 09:30:08
 * @LastEditors: Ronda
 * @LastEditTime: 2022-05-23 15:20:33
-->
<template>
  <div class="dashboard">
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="tree-panel">
          <el-input
            placeholder="搜索设备/工程"
            v-model="filterText"
            clearable
          />
          <el-tree
            class="filter-tree"
            :data="treeData"
            :props="defaultProps"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
            ref="tree"
          />
        </div>
      </el-col>

      <el-col :span="18">
        <div class="data-panel">
          <el-card shadow="hover">
            <div class="chart-header">
              <div class="indicator-tabs">
                <div
                  v-for="item in indicators"
                  :key="item.value"
                  :class="['tab-item', { active: currentIndicator === item.value }]"
                  @click="currentIndicator = item.value"
                >
                  {{ item.label }}
                </div>
              </div>
            </div>
            <div v-if="params.device_id" class="chart-container" ref="chartContainer">
              <div ref="chart" style="width: 100%; height: 300px"></div>
            </div>
            <div v-else class="no-data">请从左侧选择一个设备</div>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import axios from "axios";

export default {
  data() {
    return {
      filterText: "",
      currentIndicator: "tsp",
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      params: {
        device_id: "",
        engineer_id: "",
        page: 1,
        pageSize: 100,
      },
      chartData: {
        times: [],
        values: [],
      },
      chart: null,
      token:
        "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNzQ1NjM3NDE5LCJleHAiOjE3NDYyNDIxMTl9.v7Lv-oVgFRAnecS2piBirRBCTgzsZZZodDBTZDqoC9A",
      indicators: [
        { label: 'tsp', value: 'tsp' },
        { label: 'pm10', value: 'pm10' },
        { label: 'pm2.5', value: 'pm25' },
        { label: '温度', value: 'temperature' },
        { label: '湿度', value: 'humidity' }
      ],
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    currentIndicator() {
      this.fetchChartData();
    },
    chartData: {
      handler() {
        this.updateChart();
      },
      deep: true,
    },
  },
  created() {
    this.fetchTree();
  },
  mounted() {
    this.initChart();
    window.addEventListener("resize", this.resizeChart);
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener("resize", this.resizeChart);
  },
  methods: {
    initChart() {
      if (this.$refs.chart) {
        this.chart = echarts.init(this.$refs.chart);
      }
    },
    updateChart() {
      if (!this.chart) {
        this.initChart();
      }
      const option = {
        tooltip: {
          trigger: "axis",
          formatter: (params) => {
            const [param] = params;
            return `${param.name}<br/>${this.currentIndicator}: ${param.value}`;
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "15%",
          top: "10px",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.chartData.times,
          axisLabel: {
            rotate: 30,
            interval: 'auto',
            align: 'center',
            margin: 15,
            fontSize: 11,
            hideOverlap: true
          }
        },
        yAxis: {
          type: "value",
          name: "",
        },
        series: [
          {
            type: "line",
            data: this.chartData.values,
            areaStyle: {
              opacity: 0.3,
            },
            lineStyle: {
              width: 2,
            },
            itemStyle: {
              color: "#409EFF",
            },
            showSymbol: false,
          },
        ],
      };
      this.chart.setOption(option);
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    async fetchTree() {
      try {
        const res = await axios.get(
          "http://101.37.38.67:7001/dashboard/findEngineerDeviceTree",
          {
            headers: {
              Authorization: this.token,
            },
          }
        );
        this.treeData = res.data.data || [];
      } catch (error) {
        console.error("获取树形数据失败:", error);
        this.$message.error("获取树形数据失败");
      }
    },
    handleNodeClick(node) {
      if (!node.children) {
        this.params.device_id = node.id;
        this.params.engineer_id = node.engineer_id;
        this.fetchChartData();
      }
    },
    formatDate(date) {
      if (!date) return "";
      const d = new Date(date);
      const hour = String(d.getHours()).padStart(2, "0");
      const minute = String(d.getMinutes()).padStart(2, "0");
      return `${hour}:${minute}`;
    },
    async fetchChartData() {
      try {
        const query = {
          page: String(this.params.page),
          pageSize: String(this.params.pageSize),
          indicator: String(this.currentIndicator),
          device_id: String(this.params.device_id),
          engineer_id: String(this.params.engineer_id),
        };
        const res = await axios.get(
          "http://101.37.38.67:7001/monitor/pageQueryTodayData",
          {
            params: query,
            headers: {
              Authorization: this.token,
            },
          }
        );

        this.chartData.times =
          res.data.data?.list?.map((item) => {
            if (!item.insert_time) return "";
            const d = new Date(item.insert_time);
            const hour = String(d.getHours()).padStart(2, "0");
            const minute = String(d.getMinutes()).padStart(2, "0");
            return `${hour}:${minute}`;
          }) || [];
        this.chartData.values =
          res.data.data?.list?.map((item) => item[this.currentIndicator]) || [];
        // this.chartData = res.data.data || { times: [], values: [] }
        console.log("🚀 ~ fetchChartData ~ chartData:", this.chartData);
      } catch (error) {
        console.error("获取图表数据失败:", error);
        this.$message.error("获取图表数据失败");
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.includes(value);
    },
  },
};
</script>

<style scoped>
.dashboard {
  padding: 10px;
}
.tree-panel {
  border-right: 1px solid #eee;
  height: calc(100vh - 60px);
  overflow-y: auto;
}
.data-panel {
  padding: 10px;
}
.chart-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #E4E7ED;
}
.indicator-tabs {
  display: flex;
  position: relative;
}
.tab-item {
  padding: 8px 16px;
  cursor: pointer;
  position: relative;
  color: #909399;
  font-size: 14px;
  transition: all 0.3s;
}
.tab-item:hover {
  color: #409EFF;
}
.tab-item.active {
  color: #4fbc8d;
}
.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #409EFF;
}
.chart-container {
  height: calc(100vh - 180px);
  min-height: 400px;
}
.no-data {
  text-align: center;
  color: red;
  line-height: 300px;
}
</style>
